<?php
class Memory_service {
	
	private $ci;
	
	public function __construct()
	{
		$this->ci = & get_instance();
		$this->ci->load->model('memory_model');
		$this->ci->load->model('record_model');
		$this->ci->load->model('tag_model');
		$this->ci->load->library('utils/time_utils');
		$this->ci->load->library('utils/memory_utils');
	}
	
	public function get_last_schedule_memory($user_id, $tag_id = 0)
	{
		$memory = $this->ci->memory_model->get_schedule_memory($user_id);
		if(!$memory) $memory = $this->ci->memory_model->get_review_memory($user_id);
		return $memory;
	}
	
	public function update_memory($memory_id, $score)
	{
		$memory = $this->ci->memory_model->get_memory_by_id($memory_id);
		if(!$memory) return false;
		
		$is_review = $memory->score != 0;
		if($is_review)
		{
			$this->ci->memory_model->review_memory($memory->memoryId, $score);	
		}
		else 
		{
			$record_id = $memory->recordId;
			$memory_handled = $this->ci->memory_model->get_last_memory_handled($record_id);
			$last_ef = !$memory_handled ? 0 : $memory_handled->ef;
			$ef = $this->ci->memory_utils->evaluate_ef($last_ef, $score);
			
			$this->ci->memory_model->update_memory($memory->memoryId, $score, $ef);
			$this->add_next_memory($record_id);
		}
	}
	
	public function add_next_memory($record_id)
	{
		$record = $this->ci->record_model->get_record_by_id($record_id);
		$memory = $this->ci->memory_model->get_last_memory_handled($record_id);
		
		//$user_id, $record_id, $times, $interval, $scheduleDate
		if(!$memory)
		{
			$interval = 0;
			$today = $this->ci->time_utils->get_today();
			$this->ci->memory_model->add_memory($record->userId, $record_id, 0, $interval, $today);	
		}
		else if($memory->times == 0 || $memory->score < 3) 
		{
			//interval 1
			$times = $memory->times + 1;
			$interval = 1;
			$tomorrow = $this->ci->time_utils->get_tomorrow();
			$this->ci->memory_model->add_memory($record->userId, $record_id, $times, $interval, $tomorrow);
		}	
		else if($memory->times == 1)
		{
			//interval 6
			$times = $memory->times + 1;
			$interval = 6;
			$next_day = $this->ci->time_utils->get_next_day($interval);
			$this->ci->memory_model->add_memory($record->userId, $record_id, $times, $interval, $next_day);
		}
		else 
		{
			//last_time_interval * $ef;		
			$times = $memory->times + 1;
			$interval = $memory->intervalDays * $memory->ef;
			$next_day = $this->ci->time_utils->get_next_day($interval);
			$this->ci->memory_model->add_memory($record->userId, $record_id, $times, $interval, $next_day);
		}
	}
}
?>